{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "483ca307",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install memorizz and required dependencies\n",
    "%pip install -qU memorizz\n",
    "\n",
    "# Install Oracle database driver (required for Oracle provider)\n",
    "%pip install -qU oracledb\n",
    "\n",
    "# Install OpenAI SDK (for LLM and embeddings)\n",
    "%pip install -qU openai\n",
    "\n",
    "# Install requests (for tool examples like weather API)\n",
    "%pip install -qU requests\n",
    "\n",
    "# Install python-dotenv for .env file support (optional but recommended)\n",
    "%pip install -qU python-dotenv\n",
    "\n",
    "print(\"✅ All packages installed successfully!\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cdc3aec",
   "metadata": {},
   "outputs": [],
   "source": [
    "! memorizz install-oracle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e18f9526",
   "metadata": {},
   "outputs": [],
   "source": [
    "    import os\n",
    "\n",
    "    ORACLE_ADMIN_PASSWORD = \"MyPassword123!\"\n",
    "    ORACLE_USER = \"memorizz_user\"\n",
    "    ORACLE_PASSWORD = \"SecurePass123!\"\n",
    "    ORACLE_DSN = \"localhost:1521/FREEPDB1\"\n",
    "\n",
    "    os.environ[\"ORACLE_ADMIN_PASSWORD\"] = \"MyPassword123!\"\n",
    "    os.environ[\"ORACLE_USER\"] = \"memorizz_user\"\n",
    "    os.environ[\"ORACLE_PASSWORD\"] = \"SecurePass123!\"\n",
    "    os.environ[\"ORACLE_DSN\"] = \"localhost:1521/FREEPDB1\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "557121ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "! memorizz setup-oracle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84d7b3e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import os\n",
    "\n",
    "# Configure logging for Jupyter notebook\n",
    "os.environ['MEMORIZZ_LOG_LEVEL'] = 'INFO'\n",
    "\n",
    "# Set up proper logging configuration for notebooks\n",
    "logging.basicConfig(\n",
    "    level=logging.INFO,\n",
    "    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n",
    "    force=True  # This overwrites any existing configuration\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9886e2b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "\n",
    "# Function to securely get and set environment variables\n",
    "def set_env_securely(var_name, prompt):\n",
    "    value = getpass.getpass(prompt)\n",
    "    os.environ[var_name] = value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca8962ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "set_env_securely(\"OPENAI_API_KEY\", \"Enter your OpenAI API key: \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c10286dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "set_env_securely(\"TAVILY_API_KEY\", \"Enter your Tavily API key: \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59cfced2",
   "metadata": {},
   "outputs": [],
   "source": [
    "OPENAI_API_KEY = os.getenv(\"OPENAI_API_KEY\")\n",
    "TAVILY_API_KEY = os.getenv(\"TAVILY_API_KEY\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cbc29210",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.memory_provider.oracle import OracleProvider, OracleConfig\n",
    "\n",
    "\n",
    "# Open source model option\n",
    "HF_MODEL = \"sentence-transformers/all-MiniLM-L6-v2\" \n",
    "# Proprietary model option\n",
    "OPENAI_EMBEDDING_MODEL = \"text-embedding-3-small\" \n",
    "\n",
    "# HF_TOKEN = os.getenv(\"HF_TOKEN\")  # optional if the model is public\n",
    "huggingface_embedding_config = {\n",
    "    \"model\": HF_MODEL,\n",
    "    \"api_key\": os.getenv(\"HF_TOKEN\"),\n",
    "}\n",
    "\n",
    "# Ensure you have a valid API key and it's set in your environment\n",
    "openai_embedding_config = {\n",
    "    \"model\": OPENAI_EMBEDDING_MODEL,\n",
    "    \"api_key\": OPENAI_API_KEY,\n",
    "}\n",
    "\n",
    "# Creating a config object for the Oracle provider\n",
    "oracle_config = OracleConfig(\n",
    "    user=ORACLE_USER,\n",
    "    password=ORACLE_PASSWORD,\n",
    "    dsn=ORACLE_DSN,\n",
    "    lazy_vector_indexes=False,\n",
    "    embedding_provider=\"openai\", # or \"huggingface\" if you're using the open source model\n",
    "    embedding_config=openai_embedding_config, # or huggingface_embedding_config if you're using the open source model\n",
    ")\n",
    "\n",
    "# Creating the Oracle Memory provider using Oracle AI Database as the Memory Core\n",
    "oracle_memory_provider = OracleProvider(oracle_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5fe987d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.memagent.builders import MemAgentBuilder\n",
    "\n",
    "# Creating a config object for the Hugging Face LLM provider, use this if you're using the open source model path\n",
    "huggingface_llm_config = {\n",
    "    \"provider\": \"huggingface\",\n",
    "    \"model\": \"Qwen/Qwen2-1.5B-Instruct\",  # fully open, CPU-friendly\n",
    "    \"tokenizer\": \"Qwen/Qwen2-1.5B-Instruct\",  # optional (defaults to model id)\n",
    "    \"device\": \"cpu\",          # use \"cuda\", \"cuda:0\", or \"mps\" if you have a GPU\n",
    "    \"max_new_tokens\": 512,\n",
    "    \"temperature\": 0.2,\n",
    "    \"top_p\": 0.9,\n",
    "}\n",
    "\n",
    "# Creating a config object for the OpenAI LLM provider, use this if you're using the proprietary model path\n",
    "openai_llm_config = {\n",
    "    \"model\": \"gpt-4o-mini\",\n",
    "    \"api_key\": OPENAI_API_KEY,\n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a47cd4c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.internet_access import TavilyProvider\n",
    "\n",
    "# Ensure you have a valid API key and it's set in your environment\n",
    "tavily_internet_provider = TavilyProvider(\n",
    "    api_key=TAVILY_API_KEY,\n",
    "    config={\n",
    "        \"search_depth\": \"advanced\",     # or \"basic\"\n",
    "        \"default_max_results\": 8,       # cap per search() call\n",
    "        \"max_content_chars\": 10000,     # trim extracted pages to protect context window\n",
    "        \"include_raw_results\": False,   # True if you want Tavily’s raw JSON back\n",
    "        \"include_raw_page\": False,\n",
    "    },\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85782c37",
   "metadata": {},
   "source": [
    "```create_deep_research_agent(...)``` is a convenience helper that returns a MemAgentBuilder pre-set for Deep Research mode—hooked up with the provided (or default) internet provider, the standard multi-step research instruction, and the deep-research application mode—so you can chain on memory/config tweaks before calling .build()."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30404976",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.memagent.builders import create_deep_research_agent\n",
    "\n",
    "def build_agent(instruction: str):\n",
    "    return (\n",
    "        # Agents are created with with Tavily as the internet provider\n",
    "        create_deep_research_agent(instruction, internet_provider=tavily_internet_provider)\n",
    "        # Agents are created with with Oracle as the memory provider\n",
    "        .with_memory_provider(oracle_memory_provider)\n",
    "        # Agents are created with with OpenAI as the LLM provider\n",
    "        .with_llm_config(openai_llm_config)\n",
    "        .build()\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3f501311",
   "metadata": {},
   "outputs": [],
   "source": [
    "root_agent = build_agent(\n",
    "    \"You are the lead analyst. Break the Apple (AAPL) stock review into sub-questions \"\n",
    "    \"covering financial performance, market share, and risk outlook over the last 3 years. \"\n",
    "    \"Assign tasks, monitor progress, and coordinate synthesis.\"\n",
    ")\n",
    "\n",
    "delegate_financials = build_agent(\n",
    "    \"Financial specialist focusing on Apple’s revenue, profit, and cash flow trends \"\n",
    "    \"from the last three fiscal years. Cite filings or press releases.\"\n",
    ")\n",
    "\n",
    "delegate_market = build_agent(\n",
    "    \"Market researcher gathering Apple’s market share, major competitors, and macro headwinds \"\n",
    "    \"from the past three years.\"\n",
    ")\n",
    "\n",
    "delegate_risk = build_agent(\n",
    "    \"Risk analyst investigating regulatory, supply-chain, and innovation risks affecting Apple \"\n",
    "    \"over the same period.\"\n",
    ")\n",
    "\n",
    "synthesis_agent = build_agent(\n",
    "    \"Synthesis expert who combines delegate reports into a single memo with sections for \"\n",
    "    \"Financials, Market Landscape, and Risks. Include bullet-point insights plus references.\"\n",
    ")\n",
    "\n",
    "root_agent.save()\n",
    "delegate_financials.save()\n",
    "delegate_market.save()\n",
    "delegate_risk.save()\n",
    "synthesis_agent.save()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4072c5f",
   "metadata": {},
   "source": [
    "DeepResearchOrchestrator coordinates a MemAgent’s end‑to‑end research workflow—running the planner, delegates, and synthesis steps—so the agent can plan, browse, summarize, and report findings autonomously.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58819543",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.memagent.orchestrators import DeepResearchOrchestrator\n",
    "\n",
    "orchestrator = DeepResearchOrchestrator(\n",
    "    root_agent=root_agent,\n",
    "    delegates=[delegate_financials, delegate_market, delegate_risk],\n",
    "    synthesis_agent=synthesis_agent,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b21f2c56",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"Provide a three-year stock analysis for Apple Inc. (AAPL), highlighting financial trends, market dynamics, and key risks.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3921f9c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "report = orchestrator.execute(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4332b00",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(report)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "memorizz_local",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
